package org.jeik.beackBeans;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import org.jeik.common.Constants;
import org.jeik.controllers.MsgsController;
import org.jeik.utils.Configs;
import org.primefaces.event.FileUploadEvent;


/**
 * 
 * @author AAsha
 *
 */
@ManagedBean(name="fileUploadController")
@RequestScoped
public class FileUploadController {
	
	
	/**
	 * 
	 * @param event
	 */
	public void handleFileUpload(FileUploadEvent event) {  
		
		try {
			
            File filesDir = new File(Configs.getConfigValue(Constants.Configs.TEMP_FILES_DIR));
            
            String fileName = event.getFile().getFileName();
            
            InputStream inputStream = event.getFile().getInputstream();
            OutputStream out = new FileOutputStream(new File(filesDir, fileName));
            
            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = inputStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            
            inputStream.close();
            out.flush();
            out.close();
            
        } catch (IOException e) {
            e.printStackTrace();
        }
		
        
		MsgsController.addInfoMessage("تم رفع الملفات بنجاح");
    }
}
